package models

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	DB  *gorm.DB
	err error
)

func Init() {
	viper.SetConfigFile("conf/dev.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		fmt.Println("mysql文件读取失败")
		return
	}
	User := viper.GetString("mysql.User")
	Password := viper.GetString("mysql.Password")
	Host := viper.GetString("mysql.Host")
	Port := viper.GetInt("mysql.Port")
	Database := viper.GetString("mysql.Database")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", User, Password, Host, Port, Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("mysql连接失败")
		return
	} else {
		fmt.Println("mysql连接成功")
	}

	err = DB.AutoMigrate(&Tour{})
	if err != nil {
		fmt.Println("迁移失败")
		return
	} else {
		fmt.Println("迁移成功")
	}

}
